package com.shujia.spark.stream

import org.apache.spark.rdd.RDD
import org.apache.spark.sql.{DataFrame, SparkSession}
import org.apache.spark.streaming.dstream.ReceiverInputDStream
import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.streaming.{Durations, StreamingContext}

object Demo2DStreamToRDD {
  def main(args: Array[String]): Unit = {

    /**
      * 1、创建spark环境
      *
      */

    val spark: SparkSession = SparkSession
      .builder()
      .master("local[2]")
      .appName("dstordd")
      .config("spark.sql.shuffle.partitions", 1)
      .getOrCreate()

    import spark.implicits._
    import org.apache.spark.sql.functions._

    val sc: SparkContext = spark.sparkContext

    /**
      * 创建SparkStreaming环境
      *  Durations.seconds(5): 多久执行一次
      *
      */

    val ssc = new StreamingContext(sc, Durations.seconds(5))


    val linesDS: ReceiverInputDStream[String] = ssc.socketTextStream("master", 8888)

    /**
      * 将DStream转换成rdd,
      * Dstream的底层是每隔一段时间封装一个rdd
      *
      * 每隔一段时间执行一次foreachRDD， 每一次传进去的rdd是不一样的
      */

    linesDS.foreachRDD((rdd: RDD[String]) => {
      println("foreachRDD被执行")

      //使用rdd的api
      rdd
        .flatMap(_.split(","))
        .map((_, 1))
        .reduceByKey(_ + _)
      //.foreach(println)

      /**
        * 可以将rdd再转换成DF
        * 可以写DSL 或者sql
        *
        */

      val linesDF: DataFrame = rdd.toDF("line")

      linesDF
        .select(explode(split($"line", ",")) as "word")
        .groupBy($"word")
        .agg(count($"word") as "c")
        .show()


    })


    ssc.start()
    ssc.awaitTermination()
    ssc.stop()

  }

}
